/*
 * Copyright (c) 2020
 *
 * Change Logs:
 * Date           Author       Notes
 * 2020-08-06     chao         the first version
 */

#include <rtdevice.h>
#include <stdlib.h>

#include "beep.h"

#if defined BSP_USING_BEEP

struct rt_device_pwm     *pwm_device = RT_NULL; //定义 pwm 设备指针

/* 
 * @brief
 * @param
 * @retval
 */
int beep_init(void)
{
    /* 查找PWM设备 */
    pwm_device = (struct rt_device_pwm *)rt_device_find(BEEP_PWM_DEVICE);
    if (pwm_device == RT_NULL)
    {
        return -RT_ERROR;
    }
    return 0;
}
INIT_APP_EXPORT(beep_init);

/* 
 * @brief
 * @param
 * @retval
 */
int beep_on(void)
{
    rt_pwm_enable(pwm_device, BEEP_PWM_CH); //使能蜂鸣器对应的 PWM 通道

    return 0;
}

/* 
 * @brief
 * @param
 * @retval
 */
int beep_off(void)
{
    rt_pwm_disable(pwm_device, BEEP_PWM_CH); //失能蜂鸣器对应的 PWM 通道

    return 0;
}

/* 
 * @brief
 * @param
 * @retval
 */
int beep_set(uint16_t freq, uint8_t volume)
{
    rt_uint32_t period, pulse;

    /* 将频率转化为周期 周期单位:ns 频率单位:HZ */
    period = 1000000000 / freq;  //unit:ns 1/HZ*10^9 = ns

    /* 根据声音大小计算占空比 蜂鸣器低电平触发 */
    pulse = period - period / 100 * volume;

    /* 利用 PWM API 设定 周期和占空比 */
    rt_pwm_set(pwm_device, BEEP_PWM_CH, period, pulse);//channel,period,pulse

    return 0;
}

#if defined(RT_USING_FINSH) && defined(FINSH_USING_MSH)
/* 
 * @brief
 * @param
 * @retval
 */
void beep(int argc, char *argv[])
{
    if (argc==2)
    {
        if (rt_memcmp(argv[1], "on", 2) == 0)
        {
            beep_on();
        }
        else if (rt_memcmp(argv[1], "off", 3) == 0)
        {
            beep_off();
        }
    }
    else if (argc==4)
    {
        uint16_t freq = atoi(argv[2]);
        uint8_t volume = atoi(argv[3]);
        beep_set(freq, volume);
    }
    else
    {
        rt_kprintf("please input: beep on/off/set\n");
        rt_kprintf("e.g: beep on\n");
        rt_kprintf("e.g: beep off\n");
        rt_kprintf("e.g: beep set 300 3\n");
    }
}
MSH_CMD_EXPORT(beep, beep control on/off/set);
#endif /* defined(RT_USING_FINSH) && defined(FINSH_USING_MSH) */

#endif /* BSP_USING_BEEP */


